import { ethers } from "ethers";
import { useState } from "react";
import ErrorNotification from "./ErrorNotification";

function Resolve({ toggleResolve, issue, market, provider }) {
  const [winningOption, setWinningOption] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const handleResolve = async () => {
    try {
      setLoading(true);
      setError(null); // 清除旧错误信息

      // 检查截止时间
      const deadline = new Date(issue.deadline);
      if (deadline > new Date()) {
        setError("Deadline not passed");
        return;
      }

      const signer = await provider.getSigner();
      const transaction = await market.connect(signer).resolveIssue(issue.id, winningOption);
      await transaction.wait();
      toggleResolve();
    } catch (error) {
      console.error("Error resolving issue:", error);
      setError("Failed to resolve the issue. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-80">
      {error && <ErrorNotification message={error} onClose={() => setError(null)} />}

      <div className="p-8 border-4 border-pink-400 bg-gray-800 shadow-[6px_6px_0_#ff00ff] text-white font-pixel w-96">
        <h1 className="text-2xl text-pink-300 mb-4">Resolve: {issue.description}</h1>

        <div className="space-y-3">
          {issue.options.map((option, index) => (
            <div key={index} className="flex items-center space-x-4">
              <input
                type="radio"
                id={`option-${index}`}
                name="winningOption"
                value={index}
                checked={winningOption === index}
                onChange={() => setWinningOption(index)}
                className="w-6 h-6 accent-pink-400"
              />
              <label htmlFor={`option-${index}`} className="text-lg">{option}</label>
            </div>
          ))}
        </div>

        <div className="mt-6 flex justify-between">
          <button
            onClick={handleResolve}
            disabled={loading}
            className="px-6 py-3 border-4 border-pink-400 bg-gray-800 shadow-[4px_4px_0_#ff00ff] hover:bg-pink-500 transition"
          >
            {loading ? "Resolving..." : "Resolve"}
          </button>
          <button
            onClick={toggleResolve}
            className="px-6 py-3 border-4 border-gray-400 bg-gray-600 shadow-[4px_4px_0_#aaaaaa] hover:bg-gray-500 transition"
          >
            Cancel
          </button>
        </div>
      </div>
    </div>
  );
}

export default Resolve;
